<template>
  <div class="detail-show">
    <div class="detail-content beauty-scroller-bar" v-if="detail.id">
      <a-row type="flex" class="header">
        <a-col flex="auto" style="line-height: 32px">
          编号： {{ detail.form_id }}
        </a-col>
        <a-tooltip>
          <template #title>打印</template>
          <a-col class="print-button" v-print="printObj" @click="printClick">
            <PrinterOutlined />
          </a-col>
        </a-tooltip>
      </a-row>
      <section class="content" :gutter="[0, 12]">
        <div style="display: flex; align-items: center">
          <span class="cat-name">{{ detail.approval_name }}</span>
          <a-tag :color="colorList[detail.status]">
            {{ detail.status_txt }}
          </a-tag>
        </div>
        <div class="mt-10">
          <a-avatar
            :src="detail.user_avatar"
            style="color: #fff; background-color: #2681f3"
            :size="24"
          >
            <template #icon><UserOutlined /></template>
          </a-avatar>
          <span class="ml-10">{{ detail.user_name }}</span>
          <span class="ml-10" style="color: #888">
            {{ detail.department_name }}
          </span>
        </div>
        <a-divider />
        <div>
          <template v-for="formItem of form" :key="formItem.key">
            <div v-if="formItem.type == 'tips'" class="form-tip">
              <span>{{ formItem.setting.placeholder }}</span>
            </div>
            <a-descriptions layout="vertical" v-else :column="1">
              <a-descriptions-item
                :label="formItem.name"
                :labelStyle="{ color: '#999', marginBottom: '-10px' }"
                :contentStyle="{
                  color: '#333',
                  fontSize: '18px',
                  display: 'block',
                  width: '100%',
                }"
              >
                <div v-if="formItem.type == 'image'" class="img-box">
                  <img
                    v-for="(item, imgIndex) of formItem.value"
                    :key="imgIndex"
                    :src="item.url"
                    class="img"
                    :alt="item.name"
                    @click="previewImg(imgIndex, formItem.value)"
                  />
                </div>
                <div v-else-if="formItem.type == 'file'">
                  <a-button
                    type="link"
                    v-for="(file, fileIndex) of formItem.value"
                    :key="fileIndex"
                    @click="downloadFile(file)"
                  >
                    <template #icon>
                      <PaperClipOutlined />
                    </template>
                    {{ file.name }}
                  </a-button>
                </div>
                <div class="detail" v-else-if="formItem.type == 'detail'">
                  <a-table
                    :columns="tableData[formItem.key].columns"
                    :dataSource="tableData[formItem.key].data"
                    :scroll="{ x: 'max-content' }"
                    :pagination="false"
                    rowKey="key"
                  >
                    <template #bodyCell="{ text, column }">
                      <template v-if="column.customSlots === 'image'">
                        <a-row :gutter="[8, 12]" v-if="text && text.length">
                          <a-col
                            :span="8"
                            v-for="(item, imgIndex) of text"
                            :key="imgIndex"
                          >
                            <img
                              :src="item.url"
                              :alt="item.name"
                              class="img"
                              @click="previewImg(imgIndex, text)"
                            />
                          </a-col>
                        </a-row>
                        <span v-else>--</span>
                      </template>
                      <template v-if="column.customSlots === 'file'">
                        <div v-if="text && text.length">
                          <a-button
                            type="link"
                            v-for="(file, fileIndex) of text"
                            :key="fileIndex"
                            @click="downloadFile(file)"
                          >
                            <template #icon>
                              <PaperClipOutlined />
                            </template>
                            {{ file.name }}
                          </a-button>
                        </div>
                        <span v-else>--</span>
                      </template>
                      <template v-if="column.customSlots === 'text'">
                        <span>{{ text || "--" }}</span>
                      </template>
                    </template>
                  </a-table>
                </div>
                <span class="pre" v-else>
                  {{ formItem.value || "--" }}
                </span>
              </a-descriptions-item>
            </a-descriptions>
          </template>
        </div>
        <a-divider />
        <div class="module-title">审批进程</div>
        <a-timeline class="process" v-if="process.length">
          <a-timeline-item
            v-for="(processItem, processIndex) of process"
            :key="processItem.key"
          >
            <!-- 节点图标 -->
            <template #dot>
              <template v-if="processItem.type == 'start'">
                <div class="relative">
                  <a-avatar
                    :size="40"
                    style="color: #fff; background-color: #2681f3"
                  >
                    <template #icon><FileAddOutlined /></template>
                  </a-avatar>
                  <CheckCircleFilled class="status" :style="style.agree" />
                </div>
              </template>
              <template v-else-if="processItem.type == 'approval'">
                <div class="relative">
                  <a-avatar
                    :size="40"
                    style="color: #fff; background-color: #ff8800"
                  >
                    <template #icon><AuditOutlined /></template>
                  </a-avatar>
                  <CheckCircleFilled
                    v-if="processItem.data.agree == true"
                    class="status"
                    :style="style.agree"
                  />
                  <CloseCircleFilled
                    v-if="processItem.data.agree == false"
                    class="status"
                    :style="style.reject"
                  />
                </div>
              </template>
              <template v-else-if="processItem.type == 'deal'">
                <div class="relative">
                  <a-avatar
                    :size="40"
                    style="color: #fff; background-color: #935af6"
                  >
                    <template #icon><CarryOutOutlined /></template>
                  </a-avatar>
                  <CheckCircleFilled
                    v-if="processItem.data.agree == true"
                    class="status"
                    :style="style.agree"
                  />
                </div>
              </template>
              <template v-else-if="processItem.type == 'copy'">
                <div class="relative">
                  <a-avatar
                    :size="40"
                    style="color: #fff; background-color: #3370ff"
                  >
                    <template #icon><SisternodeOutlined /></template>
                  </a-avatar>
                  <CheckCircleFilled
                    v-if="processIndex < detail.process_now"
                    class="status"
                    :style="style.agree"
                  />
                </div>
              </template>
              <template v-else-if="processItem.type == 'end'">
                <div class="relative">
                  <a-avatar
                    :size="40"
                    style="color: #fff; background-color: #2681f3"
                  >
                    <template #icon><FileDoneOutlined /></template>
                  </a-avatar>
                  <CheckCircleFilled
                    v-if="processIndex == detail.process_now"
                    class="status"
                    :style="style.agree"
                  />
                </div>
              </template>
            </template>
            <!-- 节点内容 -->
            <div class="process-content">
              <div class="node-title">
                <span>{{ processItem.data.name || processItem.typeTxt }}</span>
                <a-tag
                  style="margin-left: 10px"
                  color="orange"
                  v-if="processItem.type == 'approval'"
                >
                  {{ processItem.data.approvalWay == 1 ? "会签" : "或签" }}
                </a-tag>
              </div>
              <!-- 发起节点 -->
              <template v-if="processItem.type == 'start'">
                <div class="flex align-middle between mt-10 flex-wrap">
                  <div class="flex align-middle no-wrap">
                    <div class="relative">
                      <a-avatar
                        :src="detail.user_avatar"
                        :size="30"
                        style="color: #fff; background-color: #2681f3"
                      >
                        <template #icon><UserOutlined /></template>
                      </a-avatar>
                      <CheckCircleFilled class="status" :style="style.agree" />
                    </div>
                    <span class="ml-10">{{ detail.user_name }}</span>
                  </div>
                  <div class="flex align-middle no-wrap ml-10">
                    <span class="text-gray">已发起</span>
                    <span class="text-gray" style="margin:0 5px; ">·</span>
                    <span class="text-gray">{{ detail.created_at }}</span>
                  </div>
                </div>
              </template>
              <!-- 审批节点 -->
              <div
                v-if="
                  processItem.type == 'approval' &&
                  processItem.data.approver_userArr &&
                  processItem.data.approver_userArr.length
                "
              >
                <template
                  v-for="item of processItem.data.approver_userArr"
                  :key="item.id"
                >
                  <div class="flex align-middle between mt-10 flex-wrap">
                    <div class="flex align-middle no-wrap">
                      <div class="relative">
                        <a-avatar
                          :src="item.avatar"
                          :size="30"
                          style="color: #fff; background-color: #2681f3"
                        >
                          <template #icon><UserOutlined /></template>
                        </a-avatar>
                        <CheckCircleFilled
                          v-if="item.op_type == 'agree'"
                          class="status"
                          :style="style.agree"
                        />
                        <CloseCircleFilled
                          v-if="item.op_type == 'reject'"
                          class="status"
                          :style="style.reject"
                        />
                      </div>
                      <span class="ml-10">{{ item.realname }}</span>
                    </div>
                    <div class="flex align-middle no-wrap" v-if="item.op_type">
                      <span class="text-gray">
                        {{ item.op_type == "agree" ? "已通过" : "已拒绝" }}
                      </span>
                      <span class="text-gray" style="margin:0 5px; ">·</span>
                      <span class="text-gray" v-if="item.op_time">
                        {{ item.op_time }}
                      </span>
                    </div>
                  </div>
                  <div
                    v-if="
                      item.op_type && item.op_type == 'reject' && item.op_reason
                    "
                    style="color: #999; font-size: 12px; padding-left: 40px"
                  >
                    拒绝原因：{{ item.op_reason }}
                  </div>

                  <div  style="margin:10px 0;background-color: #f2f3f3;border-radius: 5px;" >
                    <div style="margin: 10px">
                      <div  v-if="item.suggest_word" style="padding: 8px 0">{{item.suggest_word||'--'}}</div>
                      <div v-for="(sugImgItem,subIndex) in item?.suggest_file" :key="subIndex+100" style="display: inline-block;margin-right: 10px;margin-bottom: 5px" >
                        <a-image :src="sugImgItem" :width="32" />
                      </div>
                    </div>
                  </div>

                </template>

              </div>
              <!-- 处理节点 -->
              <div
                v-if="
                  processItem.type == 'deal' &&
                  processItem.data.dealer_userArr &&
                  processItem.data.dealer_userArr.length
                "
              >
                <div
                  v-for="item of processItem.data.dealer_userArr"
                  :key="item.id"
                  class="flex align-middle between mt-10 flex-wrap"
                >
                  <div class="flex align-middle no-wrap">
                    <div class="relative">
                      <a-avatar
                        :src="item.avatar"
                        :size="30"
                        style="color: #fff; background-color: #2681f3"
                      >
                        <template #icon><UserOutlined /></template>
                      </a-avatar>
                      <CheckCircleFilled
                        v-if="item.op_type == 'agree'"
                        class="status"
                        :style="style.agree"
                      />
                      <!-- <CloseCircleFilled
                        v-if="item.op_type == 'reject'"
                        class="status"
                        :style="style.reject"
                      /> -->
                    </div>
                    <span class="ml-10">{{ item.realname }}</span>
                  </div>
                  <div class="flex align-middle no-wrap" v-if="item.op_time">
                    <span>已办理</span>
                    <span class="ml-10 text-gray">{{ item.op_time }}</span>
                  </div>
                </div>
              </div>
              <!-- 抄送节点 -->
              <div
                v-if="
                  processItem.type == 'copy' &&
                  processItem.data.ccList_userArr &&
                  processItem.data.ccList_userArr.length
                "
              >
                <div
                  v-for="item of processItem.data.ccList_userArr"
                  :key="item.id"
                  class="flex align-middle between mt-10 flex-wrap"
                >
                  <div class="flex align-middle">
                    <div class="relative">
                      <a-avatar
                        :src="item.avatar"
                        :size="30"
                        style="color: #fff; background-color: #2681f3"
                      >
                        <template #icon><UserOutlined /></template>
                      </a-avatar>
                      <CheckCircleFilled
                        v-if="processIndex < detail.process_now"
                        class="status"
                        :style="style.agree"
                      />
                    </div>

                    <span class="ml-10">{{ item.realname }}</span>
                  </div>
                  <!-- <div class="flex align-middle">
                    <span>已抄送</span>
                    <span class="ml-10 text-gray" v-if="item.op_time">
                      {{ item.op_time }}
                    </span>
                  </div> -->
                </div>
              </div>
              <!-- 抄送人 -->
              <div
                v-if="
                  processItem.type != 'copy' &&
                  processItem.data.ccList_userArr &&
                  processItem.data.ccList_userArr.length
                "
                class="mt-10"
                style="background: #f7f7f7; padding: 10px; border-radius: 8px"
              >
                <a-row type="flex" :gutter="[24, 24]">
                  <a-col
                    v-if="
                      processIndex < detail.process_now || detail.status == 1
                    "
                  >
                    <a-tag
                      color="blue"
                      style="margin-top: 4px; margin-right: -8px"
                    >
                      已抄送至
                    </a-tag>
                  </a-col>
                  <a-col
                    v-for="item of processItem.data.ccList_userArr"
                    :key="item.id"
                  >
                    <div class="flex align-middle">
                      <a-avatar
                        :src="item.avatar"
                        :size="30"
                        style="color: #fff; background-color: #2681f3"
                      >
                        <template #icon><UserOutlined /></template>
                      </a-avatar>
                      <span class="ml-10">{{ item.realname }}</span>
                    </div>
                  </a-col>
                </a-row>
              </div>
            </div>
          </a-timeline-item>
        </a-timeline>
        <a-divider />

        <div class="comment"  v-if="detail.approverHandle">

          <div class="comment-box" :class="focus_state?'input_focus':'input_no_focus'" >
            <div class="mentions-box">
              <a-textarea v-model:value="suggest_word"  :bordered="false"  @focus="focus_state=true" @blur="focus_state=false"   placeholder="填写审批意见（选填）"  :auto-size="{ minRows: 1, maxRows: 4 }"/>
            </div>
            <div v-if="fileList.length" class="comment-images">
              <div v-for="(item,index) in fileList" :key="index" class="comment-img-box">
                <a-image
                    :width="32"
                    :src="item.url"
                />
                <close-circle-filled class="close-icon" @click="deleteImage(index)"/>
              </div>
            </div>

            <a-upload
                class="img-upload"
                :class="fileList.length==0?'img-upload-white':'img-upload-grey'"
                v-model:file-list="fileList"
                :action="$utils.imgAction"
                :headers="{ 'org-token': $store.getters.token }"
                @change="handleUploadChange"
                name="image"
                :data="{ dir: 'approval_image' }"
                accept="image/*"
                list-type="picture"
                :max-count="9"
                :showUploadList="false"
            >
              <paper-clip-outlined  style="font-size: 22px;margin-top: 5px" />
            </a-upload>


          </div>
        </div>
      </section>
    </div>
    <div class="no-content" v-else-if="!pageLoading">
      <a-empty description="无内容" />
    </div>
    <!-- 操作栏 -->
    <div
      class="option-bar"
      v-if="detail.dealerHandle || detail.approverHandle || detail.revoke == 1"
    >
      <a-space size="large">
        <a-button
          v-if="detail.dealerHandle"
          type="primary"
          key="deal"
          :loading="submitLoading"
          @click="agreeClick"
        >
          <template #icon>
            <CheckOutlined />
          </template>
          办理
        </a-button>
        <template v-if="detail.approverHandle">
          <a-button
            type="primary"
            :loading="submitLoading"
            key="agree"
            @click="agreeClick"
          >
            <template #icon>
              <CheckOutlined />
            </template>
            同意
          </a-button>

          <a-button
            type="primary"
            :loading="submitLoading"
            danger
            @click="rejectConfirm"
            key="reject"
          >
            <template #icon>
              <CloseOutlined />
            </template>
            拒绝
          </a-button>
        </template>
      </a-space>
    </div>
    <!-- 预览图片 -->
    <PreviewImg
      :visible="imgVisible"
      :index="imgIndex"
      :list="imgList"
      @close="imgVisible = false"
    />


    <!-- 打印内容 -->
    <div class="approval_print" v-if="detail.approval_id" id="printContent">
      <h1 class="approval_print_title">{{ detail.approval_name }}</h1>
      <div class="approval_print_header">
        <div class="corp_name"></div>
        <div class="approval_spNo">审批编号: {{ detail.form_id }}</div>
      </div>
      <table class="approval_print_data">
        <tr>
          <td class="approval_print_data_title">申请人</td>
          <td class="approval_print_data_value">{{ detail.user_name }}</td>
          <td class="approval_print_data_title">申请人部门</td>
          <td class="approval_print_data_value">
            {{ detail.department_name || "--" }}
          </td>
        </tr>
        <tr>
          <td class="approval_print_data_title">提交时间</td>
          <td class="approval_print_data_value">{{ detail.created_at }}</td>
          <td class="approval_print_data_title">当前审批状态</td>
          <td class="approval_print_data_value">{{ detail.status_txt }}</td>
        </tr>
        <template v-if="form && form.length > 0">
          <tr>
            <td class="approval_print_data_space" colspan="4"></td>
          </tr>
          <tr>
            <td colspan="4" class="approval_print_data_title">申请内容</td>
          </tr>
          <tr v-for="(item, index) of form" :key="index">
            <template v-if="item.type == 'detail'">
              <td
                class="approval_print_data_value approval_print_data_title_center"
              >
                {{   item.name }}
              </td>
              <td class="approval_print_data_value" colspan="3">
                <div
                  v-for="(detailItem, detailIndex) of item.value[0]"
                  :key="detailIndex"
                >
                  <template v-if="detailItem.type == 'check'">
                    {{ detailItem.value }}
                  </template>
                  <template
                    v-else-if="
                      detailItem.type == 'image' || detailItem.type == 'file'
                    "
                  >
                    <div
                      v-for="(valueItem, valueIndex) of detailItem.value"
                      :key="valueIndex"
                    >
                      <span>{{ valueIndex + 1 }}.</span>
                      <span style="margin-left: 5px">{{ valueItem.name }}</span>
                    </div>
                  </template>
                  <template v-else>
                    <span>{{ detailItem.title || detailItem.name }}：</span>
                    <span>{{ detailItem.value }}</span>
                  </template>
                </div>
              </td>
            </template>
            <template v-else>
              <td
                class="approval_print_data_value approval_print_data_title_center"
              >
                {{   item.name }}
              </td>
              <td class="approval_print_data_value" colspan="3">
                <template v-if="item.type == 'check'">
                  {{ item.value }}
                </template>
                <template
                  v-else-if="item.type == 'image' || item.type == 'file'"
                >
                  <div v-for="(item, index) of item.value" :key="index">
                    <span>{{ index + 1 }}.</span>
                    <span style="margin-left: 5px">{{ item.name }}</span>
                  </div>
                </template>
                <template v-else>
                  {{ item.value }}
                </template>
              </td>
            </template>
          </tr>
        </template>
        <tr>
          <td class="approval_print_data_space" colspan="4"></td>
        </tr>
        <tr>
          <td colspan="4" class="approval_print_data_title">
            审批流程-{{ detail.status_txt }}
          </td>
        </tr>
        <tr>
          <td
            class="approval_print_data_title approval_print_data_title_center"
          >
            审批节点
          </td>
          <td
            class="approval_print_data_title approval_print_data_title_center"
          >
            操作人
          </td>
          <td
            class="approval_print_data_title approval_print_data_title_center"
            colspan="2"
          >
            操作记录
          </td>
        </tr>
        <tr v-for="processItem of process" :key="processItem.key">
          <template v-if="processItem.type !== 'end'">
            <td
              class="approval_print_data_value approval_print_data_title_center"
            >
              <div>{{ processItem.typeTxt }}</div>
            </td>
            <!-- 发起 -->
            <template v-if="processItem.type == 'start'">
              <td
                class="approval_print_data_value approval_print_data_title_center"
              >
                {{ detail.user_name }}
              </td>
              <td
                class="approval_print_data_value approval_print_data_title_center"
                colspan="2"
              >
                <span class="text-gray">已发起</span>
                <span class="text-gray" style="margin:0 5px; ">·</span>
                <span class="text-gray">{{
                  detail.created_at.slice(0, 16)
                }}</span>
              </td>
            </template>
            <!-- 审批 -->
            <template v-else-if="processItem.type == 'approval'">
              <td
                class="approval_print_data_value approval_print_data_title_center"
                colspan="3"
                style="padding: 0"
                v-if="
                  processItem.data.approver_userArr &&
                  processItem.data.approver_userArr.length > 0
                "
              >
                <div
                  v-for="item of processItem.data.approver_userArr"
                  :key="item.id"
                  style="display: flex; align-items: center"
                >
                  <div style="width: 40%; text-align: center; padding: 4px 8px">
                    {{ item.realname }}
                  </div>
                  <template v-if="item.op_type">
                    <div
                      style="width: 60%; text-align: center; padding: 4px 8px"
                    >
                      <span class="text-gray">
                        {{ item.op_type == "agree" ? "已通过" : "已拒绝" }}
                      </span>
                      <span class="text-gray" style="margin:0 5px; ">·</span>
                      <span class="text-gray">{{
                        item.op_time.slice(0, 16)
                      }}</span>
                    </div>
                  </template>
                  <template v-else>
                    <div
                      style="
                        width: 60%;
                        text-align: center;
                        padding: 4px 8px;
                        visibility: hidden;
                      "
                    >
                      <span class="text-gray">已发起</span>
                      <span class="text-gray" style="margin:0 5px; ">·</span>
                      <span class="text-gray">{{
                        detail.created_at.slice(0, 16)
                      }}</span>
                    </div>
                  </template>
                </div>
              </td>
            </template>
            <!-- 办理 -->
            <template v-else-if="processItem.type == 'deal'">
              <td
                class="approval_print_data_value approval_print_data_title_center"
                colspan="3"
                style="padding: 0"
                v-if="
                  processItem.data.dealer_userArr &&
                  processItem.data.dealer_userArr.length > 0
                "
              >
                <div
                  v-for="item of processItem.data.dealer_userArr"
                  :key="item.id"
                  style="display: flex; align-items: center"
                >
                  <div style="width: 40%; text-align: center; padding: 4px 8px">
                    {{ item.realname }}
                  </div>
                  <template v-if="item.op_type">
                    <div
                      style="width: 60%; text-align: center; padding: 4px 8px"
                    >
                      <span class="text-gray">
                        {{ item.op_type == "agree" ? "已通过" : "已拒绝" }}
                      </span>
                      <span class="text-gray" style="margin:0 5px; ">·</span>
                      <span  class="text-gray">{{
                        item.op_time.slice(0, 16)
                      }}</span>
                    </div>
                  </template>
                  <template v-else>
                    <div
                      style="
                        width: 60%;
                        text-align: center;
                        padding: 4px 8px;
                        visibility: hidden;
                      "
                    >
                      <span class="text-gray">已发起</span>
                      <span class="text-gray" style="margin:0 5px; ">·</span>
                      <span class="text-gray">{{
                        detail.created_at.slice(0, 16)
                      }}</span>
                    </div>
                  </template>
                </div>
              </td>
            </template>
            <!-- 抄送 -->
            <template v-else-if="processItem.type == 'copy'">
              <td
                class="approval_print_data_value approval_print_data_title_center"
                colspan="3"
              >
                <span>已抄送给</span>
                <div
                  v-if="
                    processItem.data.ccList_userArr &&
                    processItem.data.ccList_userArr.length > 0
                  "
                  style="display: inline-block; margin-left: 10px"
                >
                  <span
                    v-for="(item, index) of processItem.data.ccList_userArr"
                    :key="item.id"
                  >
                    {{ item.realname
                    }}<i
                      v-if="index < processItem.data.ccList_userArr.length - 1"
                      >、</i
                    >
                  </span>
                  <span style="margin-left: 10px"
                    >共{{ processItem.data.ccList_userArr.length }}人</span
                  >
                </div>
              </td>
            </template>
          </template>
        </tr>
      </table>

      <div class="approval_print_info">
        <div class="approval_print_info_date">
          打印日期：{{ moment().format("YYYY-MM-DD HH:mm") }}
        </div>
        <br />
        <div class="approval_print_info_user" v-if="userInfo.realname">
          打印人：{{ userInfo.realname }}
        </div>
      </div>
      <div class="approval_print_qr">
        <div class="approval_print_qr_image_wrap">
          <qrcode-vue :value="codeUrl" :size="70" level="M" />
        </div>
        <p class="approval_print_qr_text">使用手机微信<br />扫一扫</p>
      </div>
    </div>
  </div>
</template>

<script>
import {defineComponent, reactive, toRaw, toRefs, watch, computed, createVNode, ref,} from "vue";
import request from "../../../../common/utils/request";
import {
  FileAddOutlined,
  UserOutlined,
  PaperClipOutlined,
  AuditOutlined,
  CarryOutOutlined,
  SisternodeOutlined,
  FileDoneOutlined,
  CheckOutlined,
  CloseOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  PrinterOutlined,
  ExclamationCircleOutlined, LinkOutlined,
} from "@ant-design/icons-vue";
import { PreviewImg } from "bl-common-vue3";
import { message, Modal } from "ant-design-vue";
import utils from "../../../../common/utils/utils";
import { useRouter } from "vue-router";
import moment from "moment";
import store from "../../../../store";
import defaultSetting from "../../../../common/utils/defaultSetting";
import print from "vue3-print-nb";
import QrcodeVue from "qrcode.vue";
const colorList = {
  0: "blue",
  1: "green",
  2: "red",
  4: "gray",
};

export default defineComponent({
  name: "DetailShow",
  props: {
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  components: {
    FileAddOutlined,
    UserOutlined,
    PaperClipOutlined,
    PreviewImg,
    AuditOutlined,
    CarryOutOutlined,
    SisternodeOutlined,
    FileDoneOutlined,
    CheckOutlined,
    CloseOutlined,
    CheckCircleFilled,
    CloseCircleFilled,
    PrinterOutlined,
    QrcodeVue,
  },
  directives: {
    print,
  },
  setup(props, { emit }) {
    const router = useRouter();
    const state = reactive({
      detail: {},
      form: [],
      tableData: {},
      imgVisible: false,
      imgIndex: 0,
      imgList: [],
      process: [],
      pageLoading: false,
      submitLoading: false,


      suggest_word:'',
      suggest_file:[],
      focus_state:false,
    });

    const previewImg = (index, list) => {
      state.imgList = list.map((item) => item.url);
      state.imgIndex = index;
      state.imgVisible = true;
    };

    const downloadFile = (file) => {
      window.open(file.url);
    };

    const agreeClick = () => {
      state.submitLoading = true;
      const params = {
        id: state.detail.id,
        handle: "agree",
        needMsg: true,
        suggest_word:state.suggest_word,
        suggest_file:state.suggest_file
      }
      request
        .put("/work_approval", "/tenant/approvalForm/approval", params)
        .then((res) => {
          if (state.detail?.alias == 'contract_retreat_approval') {
            Modal.confirm({
              title: "提示",
              icon: createVNode(ExclamationCircleOutlined),
              content: "操作成功！请前往退租合同列表查看",
              okText: "立即前往",
              cancelText: "知道了",
              onOk() {
                if (window.__POWERED_BY_QIANKUN__) {
                  window.goMainRoute({
                    name: "contractRetreat",
                  });
                } else if (window.self !== window.top) {
                  window.top.postMessage(
                    {
                      type: "toMainRoute",
                      routeName: "contractRetreat",
                    },
                    "*"
                  );
                }
              },
              onCancel() {
                getApprovalDetail();
              },
            });
          } else {
            message.success(res.msg || "操作成功！");
            getApprovalDetail();
          }
        })
        .finally(() => {
          state.submitLoading = false;
          postMessageToParent("agree");
        });
    };



    const rejectConfirm = () => {
      state.submitLoading = true;
      request
        .put("/work_approval", "/tenant/approvalForm/approval", {
          id: state.detail.id,
          handle: "reject",
          needMsg: true,
          suggest_word:state.suggest_word,
          suggest_file:state.suggest_file
        })
        .then((res) => {
          message.success("操作成功！");
          getApprovalDetail();
        })
        .finally(() => {
          state.submitLoading = false;
          postMessageToParent("reject");
        });
    };

    const postMessageToParent = (result) => {
      if (!window.__POWERED_BY_QIANKUN__ && window.self !== window.parent) {
        window.parent.postMessage(
          {
            type: "approvalFinished",
            result,
          },
          "*"
        );
      }
    };

    const getSlotsRender = (type) => {
      if (["image", "file"].includes(type)) {
        return type;
      }
      return "text";
    };

    let keyCount = 0;
    const handleTableColumns = () => {
      state.tableData = {};
      state.form.forEach((formItem) => {
        keyCount++;
        formItem.key = formItem.key || `key_${keyCount}`;
        if (formItem.type == "detail") {
          state.tableData[formItem.key] = {
            columns: formItem.formList.map((item) => ({
              title: item.name,
              key: item.key,
              dataIndex: item.key,
              width: item.type == "image" ? 300 : 180,
              customSlots: getSlotsRender(item.type),
              // ellipsis: true,
            })),
            data: formItem.value.map((item, index) => {
              let newItem = { index: `${index + 1}` };
              if (!item.key) {
                item.key = `${formItem.key}_${index}`;
              }
              item.forEach((item2, index2) => {
                if (item2.key && item2.key.indexOf("#") > -1) {
                  item2.key = item2.key.split("#")[0];
                }
                if (!item2.key) {
                  item2.key = `col_${index2}`;
                }
                let uKey = formItem.value[0][index2].key;
                newItem[uKey] = item2.value;
              });
              return newItem;
            }),
          };
          state.tableData[formItem.key].columns.unshift({
            title: "#",
            key: "index",
            dataIndex: "index",
            fixed: "left",
            width: 100,
          });
        }
      });
    };

    const getFormData = (formList) => {
      let form = [];
      formList.forEach((formItem) => {
        if (!formItem.name) {
          formItem.name = formItem.setting.name;
        }
        if (formItem.type == "daterange") {
          form.push({
            ...formItem,
            key: `${formItem.key}_start`,
            name: formItem.name[0],
            value: formItem.value.start,
          });
          form.push({
            ...formItem,
            key: `${formItem.key}_end`,
            name: formItem.name[1],
            value: formItem.value.end,
          });
          form.push({
            ...formItem,
            key: `${formItem.key}_duration`,
            name: formItem.name[2] + "（天）",
            value: formItem.value.duration,
          });
        } else {
          if (formItem.type == "check") {
            if (formItem.value) {
              formItem.value = formItem.value.join("/");
            }
          }
          if (
            (formItem.type == "image" || formItem.type == "file") &&
            formItem.value
          ) {
            if (Array.isArray(formItem.value)) {
              // 之前这么写？没有数据又套一层{}？
              // formItem.value = formItem.value.map((item) => ({
              //   name: item.name || item,
              //   url: item.url || item,
              // }));
              const tempItem = formItem.value.map((item) => ({
                url: item.url,
              }));
              formItem.value = tempItem.filter((item) => {
                return item.url;
              });
            } else {
              formItem.value = [];
            }
          }
          if (formItem.type == "detail") {
            if (!formItem.formList && formItem.value.length) {
              // 其他应用没有传formList需要根据value组装
              formItem.formList = formItem.value[0].map((item, index) => ({
                ...item,
                key: `col_${index}`,
                value: "",
              }));
            }
            formItem.formList = getFormData(formItem.formList);
            formItem.value = formItem.value.map((item) => getFormData(item));
          }
          form.push(formItem);
        }
      });
      return form;
    };

    const getApprovalDetail = () => {
      state.pageLoading = true;
      state.detail = {};
      state.process = [];
      state.form = [];
      state.suggest_word = "";
      state.suggest_file = [];
      fileList.value = [];
      request
        .get("/work_approval", "/tenant/approvalForm/get", {
          id: props.id,
        })
        .then((res) => {
          if (res.result.status != 0) {
            // 通知审批结束
            emit("finish");
          }
          state.detail = res.result;
          state.process = res.result.process;
          state.form = getFormData(state.detail.form);
          handleTableColumns();
          console.log("-------------getApprovalDetail", toRaw(state.process));
        })
        .finally(() => {
          state.pageLoading = false;
        });
    };

    // 图片
    const fileList = ref([]);
    let images = [];
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              images.push(file.url);
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        images = [];
      }
      fileList.value = resFileList;
      state.suggest_file = fileList.value.map(item=>{
        return item.url
      })
    };

    const deleteImage = (index) => {
      fileList.value.splice(index,1)
      state.suggest_file = fileList.value.map(item=>{
        return item.url
      })
    }

    const init = () => {
      if (props.id) {
        getApprovalDetail();
      }
    };

    init();

    watch(
      () => props.id,
      (id) => {
        if (id) {
          getApprovalDetail();
        } else {
          state.detail = {};
          state.process = [];
          state.form = [];
        }
      }
    );

    const printClick = (id) => {};

    const userInfo = computed(() => {
      let userInfo = {};
      if (store.getters.iframeData && store.getters.iframeData.userInfo) {
        userInfo = JSON.parse(store.getters.iframeData.userInfo);
      }
      return userInfo;
    });

    const codeUrl = computed(() => {
      let url = `${
        utils.isEnv()
          ? "https://app.kuaijingai.com"
          : defaultSetting.requestDomain
      }/h5_orgs/pages/approval/detail?org_id=${
        store.getters.userInfo.org_id
      }&id=${props.id}`;
      console.log("codeUrl", codeUrl);
      return url;
    });

    const printObj = {
      id: "printContent",
      popTitle: "资产标签",
      extraCss: `${utils.staticPath}/file/approval/PrintIframe.css`,
      extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
      beforeOpenCallback(vue) {
        vue.printLoading = true;
        console.log("打开之前");
      },
      openCallback(vue) {
        vue.printLoading = false;
        console.log("执行了打印");
      },
      closeCallback(vue) {
        console.log("关闭了打印工具");
      },
    };

    return {
      colorList,
      style: {
        agree: `color: #52c41a`,
        reject: `color: #f5222d`,
      },
      ...toRefs(state),
      previewImg,
      downloadFile,
      agreeClick,
      rejectConfirm,
      printClick,
      moment,
      userInfo,
      codeUrl,
      printObj,
      handleUploadChange,
      fileList,
      deleteImage
    };
  },
});
</script>

<style lang="less" scoped>
.detail-show {
  width: 100%;
  height: 100%;
  position: relative;
  .detail-content {
    height: 100%;
    overflow: hidden auto;
    position: relative;
    .header {
      background: #fff;
      padding: 8px 10px;
      border-bottom: 1px solid #f1f1f1;
      color: #999;

      .print-button {
        cursor: pointer;
        padding: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 4px;
        font-size: 16px;
        transition: 0.2s ease;

        &:hover {
          background-color: #f2f3f3;
        }
      }
    }
    .content {
      padding: 20px;
      .cat-name {
        font-size: 24px;
        font-weight: bold;
        margin-right: 10px;
      }
      .img-box {
        display: flex;
        align-items: center;
        .img {
          margin-right: 10px;
        }
      }
      .img {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        margin-right: 10px;
        border: 1px solid #f1f1f1;
        cursor: pointer;
      }
      .detail {
        :deep(.ant-table td) {
          overflow: hidden;
        }
      }
      .form-tip {
        padding: 10px;
        background: #f1f1f1;
        margin-bottom: 16px;
        color: #000;
      }
      // .module-title {
      // }
      .comment{
        margin-bottom: 40px;
        padding:12px 0px;
        .comment-box{
          position: relative;
          border-radius: 10px;
          padding:  10px;
          margin-bottom: 10px;


          .mentions-box{

            textarea{
              padding: 10px;
            }
          }

          .comment-images{
            height: 45px;
            padding: 13px 0 0;
            overflow: hidden;

            .comment-img-box{
              position: relative;
              display: inline-block;
              margin-right: 12px;
              width: 32px;
              height: 32px;
              border-radius: 10px;

              .close-icon{
                position: absolute;
                width: 20px;
                height: 20px;
                top: -5px;
                right: -10px;
              }
            }

          }

          .img-upload{
            position: absolute;
            display: inline-block;
            width: 32px;
            height: 32px;
            line-height: 32px;
            text-align: center;
            border-radius: 5px;
          }
        }
      }

      .img-upload-white{
        bottom:15px;
        right: 16px;
        background-color: transparent;
      }
      .img-upload-grey{
        bottom:10px;
        right: 10px;
        background-color: #DCDCDD;
      }


      .process {
        margin-top: 20px;
        padding: 20px 20px 0;
        .relative {
          position: relative;
          .status {
            position: absolute;
            right: 0;
            bottom: 0;
            z-index: 99;
            background: #fff;
            border-radius: 50%;
          }
        }

        .process-content {
          margin-left: 20px;
          padding-bottom: 20px;
          line-height: 24px;
          .node-title {
            line-height: 30px;
            font-weight: bold;
          }
        }
      }
    }
  }
  .no-content {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .option-bar {
    position: absolute;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background: #fefefe;
    height: 60px;
    border-top: 1px solid #ddd;
    display: flex;
    align-items: center;
    padding: 0 20px;
    z-index: 111;
    justify-content: flex-end;
  }

  // 打印区域
  .approval_print {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -999;
    width: 640px;
    margin: 0 auto;
    padding-top: 18px;
    font-family: "lucida Grande", Verdana, "Microsoft YaHei";
    display: none;
  }

  .approval_print_pdf {
    width: 640px;
  }

  .approval_print_title {
    margin-bottom: 20px;
    font-size: 15px;
    font-weight: bold;
    text-align: center;
  }

  .approval_print_data {
    width: 100%;
    border-spacing: 1px;
    border-collapse: collapse;
    table-layout: fixed;
  }

  .approval_print_data tr {
    border-left: 1px solid #787878;
    border-right: 1px solid #787878;
  }

  .approval_print_data_value,
  .approval_print_data_title {
    height: 18px;
    padding: 4px 8px;
    border: 1px solid #787878;
    overflow: hidden;
    word-break: break-word;
    word-wrap: break-word;
  }

  .approval_print_data_value {
    width: 30%;
    background-color: #fff;
    font-size: 12px;
  }

  .approval_print_data_title {
    width: 16%;
    background-color: #f3f3f3;
    color: #000;
    font-size: 12px;
    text-align: center;
  }

  .approval_print_data_value ul,
  .approval_print_data_value ol {
    list-style: disc;
    padding-left: 20px;
  }

  .approval_print_data_value li {
    list-style: disc;
    padding-left: 0;
  }

  .approval_print_data_value ol li {
    list-style: decimal;
  }

  .approval_print_data_value pre {
    white-space: pre-wrap;
    overflow-wrap: break-word;
    font-family: "lucida Grande", Verdana, "Microsoft YaHei";
    margin-bottom: 0;
  }

  .approval_print_data_sectionTitle {
    height: 30px;
    padding-left: 25px;
    background-color: #fff;
    font-size: 12px;
    color: #000;
  }

  .approval_print_data_space {
    height: 15px;
    background: #fff;
    border-right: 1px solid #787878;
    border-left: 1px solid #787878;
  }

  .approval_print_space_title {
    height: 20px;
    background: #f3f3f3;
    text-align: center;
    border: 1px solid #787878;
    font-size: 12px;
  }

  .approval_print_info {
    float: right;
    padding-top: 40px;
    line-height: 20px;
    font-size: 12px;
    text-align: left;
  }

  .approval_print_data_title_center {
    text-align: center;
  }

  .approval_print_info_date,
  .approval_print_info_user {
    display: inline-block;
    margin-left: 30px;
  }

  .approval_print_qr {
    height: 120px;
    display: flex;
    align-items: center;
  }

  .approval_print_qr_image_wrap img {
    vertical-align: top;
    width: 70px;
    height: 70px;
    float: left;
    margin-right: 10px;
  }

  .approval_print_qr_text {
    font-size: 12px;
    line-height: 20px;
    padding-left: 15px;
    margin-bottom: 0;
  }

  .approval_print_data_value_commentItem {
    line-height: 25px;
  }

  .print_tips_value {
    color: rgba(11, 18, 26, 0.6);
  }

  .approval_nested_table {
    width: 100%;
    height: 100%;
    border-spacing: 1px;
    border-collapse: collapse;
    table-layout: fixed;
  }

  .approval_print_data_nested {
    padding: 0;
    border: none;
  }

  .approval_print_data_nested_1 .approval_print_data_title {
    border-bottom: none;
  }

  .approval_nested_table .approval_print_data_title:last-child,
  .approval_nested_table .approval_print_data_value:last-child {
    border-right: none;
  }

  .approval_nested_table .approval_print_data_title:first-child,
  .approval_nested_table .approval_print_data_value:first-child {
    border-left: none;
  }

  .approval_nested_table tr {
    border-left: none;
    border-right: none;
  }

  .approval_print_header > div {
    margin-bottom: 4px;
    font-size: 12px;
    color: #000;
  }

  .approval_print_header .corp_name {
    float: left;
    max-width: 400px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    font-weight: 500;
  }

  .approval_print_header .approval_spNo {
    float: right;
    font-weight: 400;
  }

  .approval_print_header::after {
    content: "";
    display: inline-block;
    clear: both;
  }
}

:deep(.ant-image){
  width: 32px;
  height: 32px;
  border-radius: 10px;
  overflow: hidden;
}
.ml-10{
  margin-left: 10px;
}

.input_focus{
  border: 1px solid #2681f3;
  background: white;
}
.input_no_focus{
  border: 0 solid #2681f3;
  background: #f2f3f3;
}

.pre{
  white-space: pre;
}

</style>
